package org.tinygame.herostory;

import com.google.protobuf.GeneratedMessageV3;
import io.netty.channel.ChannelHandlerContext;
import org.tinygame.herostory.handler.CmdHandlerFactory;
import org.tinygame.herostory.handler.ICmdHandler;

import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.locks.LockSupport;

/**
 * 主线程处理器
 */
public final class MainThreadProcessor {

    private static final MainThreadProcessor instance = new MainThreadProcessor();

    //单线程 - 自实现线程，并起名
    private final ExecutorService executorService = Executors.newSingleThreadExecutor((r) ->{
        Thread thread = new Thread(r);
        thread.setName("MainThreadProcessor");
        return thread;
    });

    private MainThreadProcessor(){}

    /**
     * 获取单例对象
     * @return
     */
    public static MainThreadProcessor getInstance(){
        return instance;
    }

    /**
     * 处理消息
     * @param ctx 上下文
     * @param msg 消息对象
     */
    public void process(ChannelHandlerContext ctx, GeneratedMessageV3 msg){

        if(null == ctx || null == msg){
            return;
        }

        this.executorService.submit(() -> {

            try {
                ICmdHandler<? extends GeneratedMessageV3> cmdHandler = CmdHandlerFactory.create(msg.getClass());

                if(null != cmdHandler){
                    cmdHandler.handler(ctx,cast(msg));
                }
            }catch (Exception e){
                e.printStackTrace();
            }

        });

    }

    /**
     * 转型消息对象
     * @param msg
     * @param <Cmd>
     * @return
     */
    private static <Cmd extends GeneratedMessageV3> Cmd cast(Object msg){
        if(null == msg){
            return null;
        } else {
            return (Cmd)msg;
        }
    }

}
